import javax.swing.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @ClassName Demo02
 * @Description TODO
 * @Author Li
 * @Date 2022/9/13 11:11
 * @ModifyDate 2022/9/13 11:11
 * @Version 1.0
 */
public class Demo02 {
    // 用于处理拖动事件，表示鼠标按下时的坐标，相对于JFrame
    private static int offsetX = 0;
    private static int offsetY = 0;
    // 是否是鼠标左键移动
    private static boolean leftMouse = false;


    public static void main(String[] args) {
        JWindow window = new JWindow();
        window.setLayout(null); // 设置为空布局
        JLabel label = new JLabel("这是一个测试的JWindow窗口");
        window.add(label);
        label.setBounds(120, 130, 160, 30);
        window.setSize(400, 300); // 设置大小
        window.setLocationRelativeTo(null); // 相对屏幕居中
        window.setVisible(true); // 设置可见
        // 添加鼠标监听，实现左键拖动窗口
        window.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) { // 鼠标左键按下时记录鼠标相对窗口的位置
                if (e.getButton() == MouseEvent.BUTTON1) { // 如果是鼠标左键
                    leftMouse = true;
                    offsetX = e.getX();
                    offsetY = e.getY();
                } else {
                    leftMouse = false;
                }
            }
        });
        window.addMouseMotionListener(new MouseAdapter() { // 鼠标拖动窗口
            @Override
            public void mouseDragged(MouseEvent e) {
                if (leftMouse) {
                    int x = e.getXOnScreen() - offsetX;
                    int y = e.getYOnScreen() - offsetY;
                    window.setLocation(x, y);
                }
            }
        });
    }
}
